import {
  createRouter,
  Router,
  RouteRecordRaw,
  RouterOptions,
  createWebHashHistory,
  NavigationGuardWithThis,
} from "vue-router";
import { getLogger } from "../../ts/log";

export class YsRouteRecord {
  private readonly cfg: RouteRecordRaw;
  private children: YsRouteRecord[];

  constructor(cfg: RouteRecordRaw) {
    this.cfg = cfg;
    this.children = [];
  }

  addChildren(record: YsRouteRecord): YsRouteRecord {
    this.children.push(record);
    return this;
  }

  build(): RouteRecordRaw {
    if (this.children.length > 0) {
      const childrenCfg: RouteRecordRaw[] = [];
      this.children.forEach((value) => {
        childrenCfg.push(value.build());
      });

      this.cfg.children = childrenCfg;
    }
    return this.cfg;
  }
}

export class RouterUtil {
  private readonly cfgs: Array<RouteRecordRaw>;
  private beforeEachs: NavigationGuardWithThis<any>[];
  private logger = getLogger("ys-ts.vue.router.RouterUtil");

  constructor() {
    this.cfgs = [];
    this.beforeEachs = [];
  }

  addBeforeEach<T = any>(before: NavigationGuardWithThis<T>): RouterUtil {
    this.beforeEachs.push(before);
    return this;
  }

  addConfig(cfg: RouteRecordRaw): RouterUtil {
    this.cfgs.push(cfg);
    return this;
  }

  build(options: Partial<RouterOptions> = {}): Router {
    this.logger(`[RouterTool]`, this.cfgs);
    const router = createRouter({
      history: createWebHashHistory(),
      routes: this.cfgs,
      ...options,
    });

    this.beforeEachs.forEach((value) => {
      router.beforeEach(value);
    });

    return router;
  }
}
